<?php

/**
 * 账户相关控制器
 */

namespace app\api\controller;

use app\BaseController;
use app\common\token\TokenService;
use app\common\sms\SmsService;
use app\common\file\FileService;
use app\api\validate\Register;
use app\model\User;
use app\model\System;
use think\exception\ValidateException;
use app\common\file\ExcelService;

class Account extends BaseController
{

    protected $appid;
    protected $appSecret;

    public $data = null;

    public function __construct()
    {
        $this->appid = config('system.appid'); //微信申请对应的公众号的APPID
        $this->appSecret = config('system.appSecret'); //微信申请对应的公众号的appSecret
    }

    /**
     * 获取openid
     *
     * @return void
     */
    public function getOpenid()
    {
        $code = input('code');
        if (empty($code)) {
            error('code不能为空');
        }

        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$this->appid.'&secret='.$this->appSecret.'&js_code='.$code.'&grant_type=authorization_code';
        $res = http_get($url);
        $res = json_decode($res, true);
        if (isset($res['errcode'])) {
            error($res['errmsg']);
        }
        success('openid', $res);
    }
    
    /**
     * 通过openid获取手机号
     *
     * @return void
     */
    public function getMobileByOpenid()
    {
        $mobile_data = [
            'openid'         => input('openid'),
            'session_key'    => input('session_key'),
            'iv'             => input('iv'),
            'encrypted_data' => input('encrypted_data')
        ];

        if (empty($mobile_data['session_key']) || empty($mobile_data['iv']) || empty($mobile_data['encrypted_data'])) {
            error('缺少参数');
        }
        $mobile_data['encrypted_data'] = urldecode($mobile_data['encrypted_data']);
        $mobile_data['iv'] = urldecode($mobile_data['iv']);
        $phone = decryptData($this->appid, $mobile_data['session_key'], $mobile_data['encrypted_data'], $mobile_data['iv']); //解密密钥
        success('手机号', $phone);
    }

    /**
     * 登录
     *
     * @return void
     */
    public function login()
    {
        $login_data = [
            'mobile'       => input('mobile'),
            'password'     => input('password'),
            'sms_code'     => input('sms_code'),
            'sms_code_key' => input('sms_code_key'),
            'openid'       => input('openid'),
            'type'         => input('type'),
            'attr'         => input('attr')
        ];

        if (empty($login_data['type'])) {
            error('type不能为空');
        }
        // 1为微信登录 2为手机号密码登录 3为手机号验证码登录
        if ($login_data['type'] == 1) {
            if (empty($login_data['openid'])) {
                error('缺少参数');
            }
        }
        if ($login_data['type'] == 2) {
            if (empty($login_data['mobile']) || empty($login_data['password'])) {
                error('缺少参数');
            }
        }
        if ($login_data['type'] == 3) {
            if (empty($login_data['mobile']) || empty($login_data['sms_code_key']) || empty($login_data['sms_code'])) {
                error('缺少参数');
            }
            SmsService::checkSmsCode($login_data['sms_code_key'], $login_data['sms_code']);
        }

        $user = User::login($login_data);
        if (empty($user)) {
            error('没有此用户');
        }
        if ($user['status'] == 1) {
            error('此账号已被冻结');
        }
        $jwt_data = TokenService::getToken($user['id']);
        $data = [
            'user_id' => $user['id'],
            'attr'    => $user['attr'],
            'type'    => $user['type'],
            'cause'   => $user['cause'],
            'token'   => $jwt_data
        ];
        success('登录成功', $data);
    }

    /**
     * 注册
     *
     * @return void
     */
    public function register()
    {
        $register_data = [
            'mobile'       => input('mobile'),
            'password'     => trim(input('password')),
            'sms_code'     => input('sms_code'),
            'sms_code_key' => input('sms_code_key'),
        ];
        // 校验数据
        try {
            validate(Register::class)->check($register_data);
        } catch (ValidateException $e) {
            error($e->getError());
        }
        // 校验验证码
        SmsService::checkSmsCode($register_data['sms_code_key'], $register_data['sms_code']);
        // 注册
        $res = User::register($register_data);
        if ($res === true) {
            success('注册成功');
        } else {
            error('注册失败');
        }
    }

    /**
     * 忘记密码,通过短信修改
     *
     * @return void
     */
    public function forgetPassword()
    {
        $forget_password_data = [
            'mobile'       => input('mobile'),
            'password'     => input('password'),
            'sms_code'     => input('sms_code'),
            'sms_code_key' => input('sms_code_key')
        ];

        if (empty($forget_password_data['mobile']) || empty($forget_password_data['password']) || empty($forget_password_data['sms_code']) || empty($forget_password_data['sms_code_key'])) {
            error('缺少参数');
        }
        
        SmsService::checkSmsCode($forget_password_data['sms_code_key'], $forget_password_data['sms_code']);

        $res = User::forgetPassword($forget_password_data);
        if ($res === true) {
            success('修改成功');
        } else {
            error('修改失败');
        }
    }

    /**
     * 发送短信
     *
     * @return void
     */
    public function sendSms()
    {
        $mobile = input('mobile');
        if (empty($mobile)) {
            error('手机号不能为空');
        }
        $res = SmsService::sendZtSms($mobile);
        System::where('id', 1)->inc('sms_num')->update();
        success('发送成功', $res);
    }

    /**
     * 上传文件
     *
     * @return void
     */
    public function upload()
    {
        $file = \request()->file('file');
        if (!$file) {
            error('文件不能为空');
        }
        $res = FileService::uploadFile($file);
        success('成功', $res);
    }
}
